package com.luck.easyfoodbatch.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.adapter.DomesticAdapter;
import com.luck.easyfoodbatch.adapter.HomeShopAdapter;
import com.luck.easyfoodbatch.adapter.ImportAdapter;
import com.luck.easyfoodbatch.adapter.NetworkImageHolderView;
import com.luck.easyfoodbatch.adapter.RecyclingPagerAdapter;
import com.luck.easyfoodbatch.custom.ClipViewPager;
import com.luck.easyfoodbatch.custom.ScalePageTransformer;
import com.luck.easyfoodbatch.db.MessageDB;
import com.luck.easyfoodbatch.entity.User;
import com.luck.easyfoodbatch.mvp.home.ClassListsModel;
import com.luck.easyfoodbatch.mvp.home.ClassListsPresenter;
import com.luck.easyfoodbatch.mvp.home.ClassListsView;
import com.luck.easyfoodbatch.mvp.home.HomeBannerModel;
import com.luck.easyfoodbatch.mvp.home.HomeBannerPresenter;
import com.luck.easyfoodbatch.mvp.home.HomeBannerView;
import com.luck.easyfoodbatch.mvp.home.HomeGoodsListModel;
import com.luck.easyfoodbatch.mvp.home.HomeGoodsListPresenter;
import com.luck.easyfoodbatch.mvp.home.HomeGoodsListView;
import com.luck.easyfoodbatch.mvp.model.BannerModel;
import com.luck.easyfoodbatch.mvp.model.ClassModel;
import com.luck.easyfoodbatch.mvp.model.HomeGoods;
import com.luck.easyfoodbatch.ui.HomeWebViewActivity;
import com.luck.easyfoodbatch.ui.LocationActivity;
import com.luck.easyfoodbatch.ui.LoginActivity;
import com.luck.easyfoodbatch.ui.MessageActivity;
import com.luck.easyfoodbatch.ui.ScanActivity;
import com.luck.easyfoodbatch.ui.SearchActivity;
import com.luck.easyfoodbatch.ui.ShopDetailsActivity;
import com.luck.easyfoodbatch.ui.ShopHomeActivity;
import com.luck.easyfoodbatch.ui.ShopListActivity;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.SharedPreferencesUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;
import com.luck.easyfoodbatch.util.Utils;
import com.luck.easyfoodbatch.zxing.ui.CaptureActivity;
import com.luck.easyrecyclerview.EasyRecyclerView;
import com.luck.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.luck.easyrecyclerview.decoration.RecycleViewDivider;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * author：luck
 * project：EasyFoodBatch
 * package：com.luck.easyfoodbatch.fragment
 * email：893855882@qq.com
 * data：16/9/22
 */
public class HomeFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, RecyclerArrayAdapter.OnLoadMoreListener, OnItemClickListener, HomeBannerView, ClassListsView, HomeGoodsListView {

    @BindView(R.id.ll_city)
    LinearLayout ll_city;
    @BindView(R.id.ll_top)
    LinearLayout ll_top;
    @BindView(R.id.input_search_query)
    TextView inputSearchQuery;
    @BindView(R.id.button_search)
    ImageButton buttonSearch;
    @BindView(R.id.ib_sys)
    ImageButton buttonSys;
    @BindView(R.id.searchBarContainer)
    RelativeLayout searchBarContainer;
    @BindView(R.id.ll_right_title)
    LinearLayout ll_right_title;
    @BindView(R.id.ll_search_title)
    LinearLayout ll_search_title;
    @BindView(R.id.recyclerView)
    EasyRecyclerView recyclerView;
    @BindView(R.id.iv_message)
    ImageView iv_message;
    @BindView(R.id.tv_city)
    TextView tv_city;

    private ImageView iv_top1;
    private ImageView iv_top2;
    private ImageView iv_top3;
    private ImageView iv_top4;
    private ViewFlipper vf_headline;

    private ClipViewPager mViewPager;
    private MyPageAdapter mPageAdapter;

    private View rootView;
    private ConvenientBanner convenientBanner;
    private HomeShopAdapter adapter;
    private List<HomeGoods.DataBean> list = new ArrayList<>();
    private List<BannerModel.DataBean> images = new ArrayList<>();
    private HomeBannerModel bannerModel;
    private ClassListsModel listsModel;
    private RecyclerView importx_recyclerView, domestic_recyclerView;
    private ImportAdapter importAdapter;
    private DomesticAdapter domesticAdapter;
    private List<ClassModel.DataBean.ImportBean> importX = new ArrayList<>();
    private List<ClassModel.DataBean.ImportBean> domestic = new ArrayList<>();
    private List<ClassModel.DataBean.HomeClassBean> homeClass = new ArrayList<>();
    private int isRefresh = 0;
    private HomeGoodsListModel listModel;
    private MessageDB messageDB;
    private static final int REQUEST_QRCODE = 0x01;
    private int mDistanceY = 0;  //滑动距离

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fc_home, container, false);
            ButterKnife.bind(this, rootView);
            setTranslucentStatus(true);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(0, getStatusBarHeight(getActivity()), 0, 0);
            Log.e("********************", getStatusBarHeight(getActivity()) + "");
            initViews();
        }
        return rootView;
    }

    /**
     * 初始化
     */
    private void initViews() {
        String p_name = (String) SharedPreferencesUtil.getData(getActivity(), HttpUtil.P_NAME, "上海");
        final String p_id = (String) SharedPreferencesUtil.getData(getActivity(), HttpUtil.P_ID, "3");
        messageDB = new MessageDB(getActivity());
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL, Utils.dip2px(mContext, 0.5F), getResources().getColor(R.color.line_color)));
        recyclerView.setLayoutManager(manager);
        adapter = new HomeShopAdapter(mContext);
        adapter.addHeader(new RecyclerArrayAdapter.ItemView() {
            @Override
            public View onCreateView(ViewGroup parent) {
                View pageView = LayoutInflater.from(mContext).inflate(R.layout.viewpage_title, null);
                convenientBanner = (ConvenientBanner) pageView.findViewById(R.id.convenientBanner);
                importx_recyclerView = (RecyclerView) pageView.findViewById(R.id.importx_recyclerView);
                domestic_recyclerView = (RecyclerView) pageView.findViewById(R.id.domestic_recyclerView);
                bannerModel = new HomeBannerPresenter(HomeFragment.this, mContext);
                if (!Tools.isNull(p_id)) {
                    bannerModel.getHomeBanner(p_id);
                }
                listsModel = new ClassListsPresenter(HomeFragment.this, mContext);
                listsModel.getClassList(0, isRefresh, "8");
                importx_recyclerView.setItemAnimator(new DefaultItemAnimator());
                StaggeredGridLayoutManager manager1 = new StaggeredGridLayoutManager(4, GridLayoutManager.VERTICAL);
                importx_recyclerView.setLayoutManager(manager1);
                importAdapter = new ImportAdapter(mContext);
                importx_recyclerView.setAdapter(importAdapter);
                importAdapter.setOnItemClickListener(new ImportAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(int position, View v) {
                        ClassModel.DataBean.ImportBean bean = importX.get(position);
                        Bundle bundle = new Bundle();
                        bundle.putString("cid", bean.getCid());
                        startAct(ShopListActivity.class, bundle);
                    }
                });
                //国产特价批
                domestic_recyclerView.setItemAnimator(new DefaultItemAnimator());
                StaggeredGridLayoutManager manager2 = new StaggeredGridLayoutManager(4, GridLayoutManager.VERTICAL);
                domestic_recyclerView.setLayoutManager(manager2);
                domesticAdapter = new DomesticAdapter(mContext);
                domestic_recyclerView.setAdapter(domesticAdapter);
                domesticAdapter.setOnItemClickListener(new DomesticAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(int position, View v) {
                        ClassModel.DataBean.ImportBean bean = domestic.get(position);
                        Bundle bundle = new Bundle();
                        bundle.putString("cid", bean.getCid());
                        startAct(ShopListActivity.class, bundle);
                    }
                });
                //广告头条头部
                vf_headline = (ViewFlipper) pageView.findViewById(R.id.vf_home_headline);
                vf_headline.addView(View.inflate(mContext, R.layout.view_advertisement, null));
                vf_headline.setOnClickListener(new headerOnClick());
                //viewPage滑动
                mViewPager = (ClipViewPager) pageView.findViewById(R.id.vpShow);
                mViewPager.setPageTransformer(true, new ScalePageTransformer());
                pageView.findViewById(R.id.page_container).setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        return mViewPager.dispatchTouchEvent(event);
                    }
                });
                mViewPager.setPageMargin(40);
                mPageAdapter = new MyPageAdapter(mContext);
                mViewPager.setAdapter(mPageAdapter);
                initData();
                mViewPager.setCurrentItem(1);
                iv_top1 = (ImageView) pageView.findViewById(R.id.iv_top1);
                iv_top2 = (ImageView) pageView.findViewById(R.id.iv_top2);
                iv_top3 = (ImageView) pageView.findViewById(R.id.iv_top3);
                iv_top4 = (ImageView) pageView.findViewById(R.id.iv_top4);
                iv_top1.setOnClickListener(new headerOnClick());
                iv_top2.setOnClickListener(new headerOnClick());
                iv_top3.setOnClickListener(new headerOnClick());
                iv_top4.setOnClickListener(new headerOnClick());
                return pageView;
            }

            @Override
            public void onBindView(View headerView) {

            }
        });
        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                View transitionView = v.findViewById(R.id.iv_banner);
                Intent intent = new Intent(getActivity(),ShopDetailsActivity.class);
                HomeGoods.DataBean bean = list.get(position);
//                Bundle bundle = new Bundle();
//                bundle.putString("gid", bean.getGid() + "");
                 intent.putExtra("gid", bean.getGid() + "");
                ActivityOptionsCompat transitionActivityOptions =
                        ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity(), transitionView, "secondSharedView"
                        );

                ActivityCompat.startActivity(getActivity(),
                        intent, transitionActivityOptions.toBundle());
//                startAct(ShopDetailsActivity.class, bundle);


            }
        });
        adapter.setError(R.layout.view_error).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adapter.resumeMore();
            }
        });

        listModel = new HomeGoodsListPresenter(this, mContext);
        if (!Tools.isNull(p_id)) {
            listModel.requestHomeList(p_id);
        }

        adapter.addAll(list);
        recyclerView.setAdapter(adapter);
        recyclerView.setRefreshListener(this);
        //设置标题栏滑动渐变
        recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                //滑动的距离
                mDistanceY += dy;
                int height = convenientBanner.getHeight();
                if (mDistanceY <= 0) {
                    ll_top.setBackgroundColor(Color.TRANSPARENT);
                } else if (mDistanceY > 0 && mDistanceY <= height) {
                    float scale = (float) mDistanceY / height;
                    float alpha = (255 * scale);
                    ll_top.setBackgroundColor(Color.argb((int) alpha, 241, 58, 58));
                } else {
                    ll_top.setBackgroundColor(Color.rgb(241, 58, 58));
                }
            }
        });
        if (!Tools.isNull(p_name)) {
            tv_city.setText(p_name);
        } else {
            tv_city.setText("");
        }
    }

    private void initData() {
        List<Integer> vpList = new ArrayList<>();
        vpList.add(R.mipmap.a);
        vpList.add(R.mipmap.b);
        vpList.add(R.mipmap.c);
        vpList.add(R.mipmap.d);
        vpList.add(R.mipmap.e);
        vpList.add(R.mipmap.a);
        vpList.add(R.mipmap.b);
        vpList.add(R.mipmap.c);

        //设置OffscreenPageLimit
        mViewPager.setOffscreenPageLimit(Math.min(list.size(), 5));
        mPageAdapter.addAll(vpList);
    }

    private String role = "0";
    private List<Integer> roles = new ArrayList<>();// 权限标识

    @OnClick({R.id.input_search_query, R.id.ll_right_title, R.id.ll_city, R.id.ib_sys})
    public void onClick(View view) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.input_search_query:
                startAct(SearchActivity.class);
                getActivity().overridePendingTransition(R.anim.fade, R.anim.hold);
                break;
            case R.id.ll_right_title:
                if (isCheckedLogin()) {
                    user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
                    role = user.getRole();
                    roles.clear();
                    String[] split = role.split(",");
                    for (String code : split) {
                        if (!Tools.isNull(code)) {
                            roles.add(Integer.parseInt(code));
                        }
                    }
                    // 运营不能访问聊天
                    if (roles.size() > 1) {
                        if (roles.contains(1)) {
                            startAct(MessageActivity.class);
                        } else {
                            T.showAnimToast(mContext, "抱歉，您没有操作权限~");
                        }
                    } else {
                        if (roles.contains(2) || roles.contains(3)) {
                            T.showAnimToast(mContext, "抱歉，您没有操作权限~");
                        } else {
                            startAct(MessageActivity.class);
                        }
                    }
                } else {
                    startAct(LoginActivity.class);
                }
                break;
            case R.id.ll_city:
                intent.setClass(mContext, LocationActivity.class);
                startActivityForResult(intent, 200);
                break;
            case R.id.ib_sys:
                Intent intent1 = new Intent(getContext(), CaptureActivity.class);
                startActivityForResult(intent1, REQUEST_QRCODE);
                break;

        }
    }

    /**
     * 头部点击事件
     */
    public class headerOnClick implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            Bundle bundle = new Bundle();
            switch (view.getId()) {
                case R.id.iv_top1:
                    bundle.putString("country_type", "2");
                    bundle.putString("nature", "3");
                    startAct(ShopListActivity.class, bundle);
                    break;
                case R.id.iv_top2:
                    bundle.putString("country_type", "1");
                    bundle.putString("nature", "3");
                    startAct(ShopListActivity.class, bundle);
                    break;
                case R.id.iv_top3:
                    bundle.putString("order", "1");//1 ,按销量排序
                    startAct(ShopListActivity.class, bundle);
                    break;
                case R.id.iv_top4:
                    bundle.putString("order", "2"); //2,按日期排序
                    startAct(ShopListActivity.class, bundle);
                    break;
                case R.id.vf_home_headline:
                    showToast("你点击了头条");
                    break;
            }
        }
    }

    /**
     * 设置新消息提醒，聊天或系统消息
     */
    public void initMessage(int count) {
        if (iv_message != null) {
            if (isCheckedLogin()) {
                int msgCountTotal = getUnreadMsgCountTotal();
                int messagesCount = messageDB.getByAllMessagesCount();
                if (messagesCount > 0 || msgCountTotal > 0) {
                    iv_message.setImageResource(R.mipmap.home_message_white);
                } else {
                    iv_message.setImageResource(R.mipmap.home_xiaoxi_white);
                }
            }
           /* if (count > 0) {
                iv_message.setImageResource(R.mipmap.home_xiaoxi_01_1x);
            } else {
                iv_message.setImageResource(R.mipmap.home_xiaoxi_00_1x);
            }*/
        }
    }

    @Override
    public void getBannerSuccess(BannerModel model) {
        if (model.getStatus() == HttpUtil.RESULT_OK) {
            if (model.getData() != null && model.getData().size() > 0) {
                images = model.getData();
            } else {
                images = new ArrayList<>();
            }
            recyclerView.getSwipeToRefresh().setRefreshing(false);
            convenientBanner.setPages(
                    new CBViewHolderCreator<NetworkImageHolderView>() {
                        @Override
                        public NetworkImageHolderView createHolder() {
                            return new NetworkImageHolderView();
                        }
                    }, images)
                    //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                    .setPageIndicator(new int[]{R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused})
                    //设置指示器的方向
                    .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                    //.setPageTransformer(new DefaultTransformer())
                    //.setOnPageChangeListener(this)//监听翻页事件
                    .setOnItemClickListener(HomeFragment.this);
            convenientBanner.startTurning(3000);
        }
    }

    @Override
    public void getHomeClassSuccess(ClassModel model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                ClassModel.DataBean data = model.getData();
                importX = data.getImportX();// 进口
                if (importX == null) {
                    importX = new ArrayList<>();
                }
                domestic = data.getDomestic();// 国产
                if (this.domestic == null) {
                    this.domestic = new ArrayList<>();
                }
                importAdapter.setList(importX);
                importAdapter.notifyDataSetChanged();
                domesticAdapter.setList(this.domestic);
                domesticAdapter.notifyDataSetChanged();
                recyclerView.getSwipeToRefresh().setRefreshing(false);

                homeClass = data.getHome_class();
                try {
                    if (homeClass.size() > 0) {
                        String img1 = homeClass.get(0).getImg();
                        String img2 = homeClass.get(1).getImg();
                        String img3 = homeClass.get(2).getImg();  //平台热销
                        String img4 = homeClass.get(3).getImg();  //新品上线
                        Glide.with(App.getInstance())
                                .load(HttpUtil.IMG_BASE_URL + img1)
                                .diskCacheStrategy(DiskCacheStrategy.ALL)
                                .into(iv_top1);
                        Glide.with(App.getInstance())
                                .load(HttpUtil.IMG_BASE_URL + img2)
                                .diskCacheStrategy(DiskCacheStrategy.ALL)
                                .into(iv_top2);
                        Glide.with(App.getInstance())
                                .load(HttpUtil.IMG_BASE_URL + img3)
                                .diskCacheStrategy(DiskCacheStrategy.ALL)
                                .into(iv_top4);
                        Glide.with(App.getInstance())
                                .load(HttpUtil.IMG_BASE_URL + img4)
                                .diskCacheStrategy(DiskCacheStrategy.ALL)
                                .into(iv_top3);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void getHomeListSuccess(HomeGoods model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                list = model.getData();
                if (list == null) {
                    list = new ArrayList<>();
                }
                adapter.clear();
                adapter.addAll(list);
                adapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void httpStatusError() {
    }

    @Override
    public void hideLoading() {
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isCheckedLogin()) {
            int msgCountTotal = getUnreadMsgCountTotal();
            int messagesCount = messageDB.getByAllMessagesCount();
            if (messagesCount > 0 || msgCountTotal > 0) {
                iv_message.setImageResource(R.mipmap.home_message_white);
            } else {
                iv_message.setImageResource(R.mipmap.home_xiaoxi_white);
            }
        }
        //开始自动翻页
        if (convenientBanner != null) {
            convenientBanner.startTurning(3000);
        }
    }

    /**
     * get unread message count
     * 获取聊天未读消息数量
     *
     * @return
     */
    public int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;
        int chatroomUnreadMsgCount = 0;
        unreadMsgCountTotal = EMClient.getInstance().chatManager().getUnreadMsgsCount();
        for (EMConversation conversation : EMClient.getInstance().chatManager().getAllConversations().values()) {
            if (conversation.getType() == EMConversation.EMConversationType.ChatRoom)
                chatroomUnreadMsgCount = chatroomUnreadMsgCount + conversation.getUnreadMsgCount();
        }
        return unreadMsgCountTotal - chatroomUnreadMsgCount;
    }

    @Override
    public void onPause() {
        super.onPause();
        if (convenientBanner != null) {
            convenientBanner.stopTurning();
        }
    }


    @Override
    public void onRefresh() {
        isRefresh = 1;
        String p_id = (String) SharedPreferencesUtil.getData(getActivity(), HttpUtil.P_ID, "");
        listsModel.getClassList(0, isRefresh, "8");
        if (Tools.isNull(p_id)) {
            p_id = "3";
        }
        listModel.requestHomeList(p_id);
        bannerModel.getHomeBanner(p_id);
    }

    @Override
    public void onLoadMore() {

    }

    @Override
    public void onItemClick(int position) {
        Bundle bundle = new Bundle();
        BannerModel.DataBean bean = images.get(position);
        int type = bean.getType();
        switch (type) {
            case 0:
                // 外部链接
                bundle.putString("url", bean.getHref());
                startAct(HomeWebViewActivity.class, bundle);
                break;
            case 1:
                // 商品 =1时就跳商品详情
                bundle.putString("gid", bean.getHid() + "");
                startAct(ShopDetailsActivity.class, bundle);
                break;
            case 2:
                // 店铺 =2时跳店铺详情
                bundle.putString("shop_id", bean.getHid() + "");
                startAct(ShopHomeActivity.class, bundle);
                break;
        }
    }

    /**
     * 设置定位
     */
    public void initCity() {
        String p_name = (String) SharedPreferencesUtil.getData(getActivity(), HttpUtil.P_NAME, "");
        String p_id = (String) SharedPreferencesUtil.getData(getActivity(), HttpUtil.P_ID, "");
        if (!Tools.isNull(p_name)) {
            tv_city.setText(p_name);
        } else {
            tv_city.setText("");
        }
        if (bannerModel == null) {
            bannerModel = new HomeBannerPresenter(HomeFragment.this, mContext);
        }
        bannerModel.getHomeBanner(p_id);
        listModel.requestHomeList(p_id);
        Log.i("location success", p_name);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_QRCODE:
                if (resultCode == Activity.RESULT_OK) {
                    String scan_result = data.getStringExtra("SCAN_RESULT");
                    if (scan_result.contains("http") || scan_result.contains("https")) {
                        //打开链接
                        /*Intent intent = new Intent(this, AdBrowserActivity.class);
                        intent.putExtra(AdBrowserActivity.KEY_URL, code);
                        startActivity(intent);*/
                    } else {
                        Intent intent = new Intent(mContext, ScanActivity.class);
                        intent.putExtra("scan_result", scan_result);
                        startActivity(intent);
                        //showToast(scan_result);
                    }

                } else if (resultCode == 300) {
                    //从本地相册扫描后的业务逻辑
                    String local_photo_result = data.getStringExtra("LOCAL_PHOTO_RESULT");
                    Toast.makeText(getActivity(), local_photo_result, Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    //    class MyPageAdapter extends PagerAdapter {
//        List<Integer> mList;
//        Context mContext;
//
//        public MyPageAdapter(Context context) {
//            mList = new ArrayList<>();
//            mContext = context;
//        }
//
//
//        @Override
//        public int getCount() {
//            return mList.size();
//        }
//
//        @Override
//        public Object instantiateItem(ViewGroup container, final int position) {
//            ImageView view = new ImageView(mContext);
//            view.setScaleType(ImageView.ScaleType.FIT_XY);
//            view.setImageResource(mList.get(position));
//            view.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    Toast.makeText(mContext, "这是图片" + position, Toast.LENGTH_SHORT).show();
//                }
//            });
//            container.addView(view);
////                view.setAdjustViewBounds(true);
//            return view;
//        }
//
//        @Override
//        public boolean isViewFromObject(View view, Object o) {
//            return view == o;
//        }
//
//        public void addAll(List<Integer> list) {
//            mList.addAll(list);
//            notifyDataSetChanged();
//        }
//
//        @Override
//        public void destroyItem(ViewGroup container, int position, Object object) {
//            container.removeView((View) object);
//        }
//    }
    public class MyPageAdapter extends RecyclingPagerAdapter {

        private final List<Integer> mList;
        private final Context mContext;

        public MyPageAdapter(Context context) {
            mList = new ArrayList<>();
            mContext = context;
        }

        public void addAll(List<Integer> list) {
            mList.addAll(list);
            notifyDataSetChanged();
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup container) {
            ImageView imageView = null;
            if (convertView == null) {
                imageView = new ImageView(mContext);
            } else {
                imageView = (ImageView) convertView;
            }
            imageView.setTag(position);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setImageResource(mList.get(position));
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(mContext, "你点击了" + position, Toast.LENGTH_SHORT).show();
                }
            });
            return imageView;
        }

        @Override
        public int getCount() {
            return mList.size();
        }
    }

}
